<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :inline="true"
        ref="queryForm"
        @submit.native.prevent
        :model="queryParams"
        label-width="95px"
      >
        <el-form-item label="重要数据名称" prop="tagName">
          <common-input
            v-model="queryParams.tagName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="重要数据来源" prop="tagSource">
          <el-select placeholder="请选择" v-model="queryParams.tagSource">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="数据分类" :value="1"></el-option>
            <el-option label="关键字" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据分类" prop="typeId">
          <div class="maxRowsDiv">
            <el-cascader
              style="width: 100%"
              :options="treeListArr"
              :show-all-levels="false"
              v-model="queryParams.typeId"
              :props="{
                label: 'typeName',
                value: 'typeId',
                emitPath: false,
              }"
              checkStrictly
              clearable
              ref="cascader"
            >
              <template slot-scope="{ node, data }">
                <common-marquee-text
                  :content="data.typeName"
                ></common-marquee-text>
              </template>
            </el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="关键字" prop="keyWord">
          <common-input
            v-model="queryParams.keyWord"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select placeholder="请选择" v-model="queryParams.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 中-->
    <div slot="tools">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        @click="handleAdd"
        v-hasPermi="['datascan:tags:add']"
        >新增
      </el-button>
      <el-button
        type="danger"
        plain
        :disabled="!showBatch"
        icon="el-icon-delete"
        @click="handleDelete()"
        v-hasPermi="['datascan:tags:remove']"
        >批量删除
      </el-button>
    </div>
    <!--  表-->
    <common-table
      slot="content"
      :data="valueList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="重要数据名称"
        align="left"
        prop="tagName"
        width="150"
        fixed="left"
        show-overflow-tooltip
      />
      <el-table-column
        label="重要数据来源"
        align="left"
        prop="tagSource"
        show-overflow-tooltip
        width="150"
      />
      <el-table-column
        label="数据分类"
        align="left"
        prop="typeIds"
        width="400px"
        show-overflow-tooltip
      />
      <el-table-column
        label="关键字"
        align="left"
        prop="keyWord"
        width="300px"
        show-overflow-tooltip
      />
      <el-table-column
        label="备注"
        align="left"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column label="状态" align="center" prop="status" width="100px">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === 0">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status === 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="125px" fixed="right">
        <template slot-scope="scope">
          <!-- <el-button type="text" @click="getInfo(scope.row.tagId)"
            >详情
          </el-button> -->
          <el-button
            type="text"
            v-hasPermi="['datascan:tags:edit']"
            @click="handleShake(scope.row)"
            :disabled="scope.row.isDisabledForShake"
          >
            <span v-if="scope.row.status === 1">启用</span>
            <span v-if="scope.row.status === 0">停用</span>
          </el-button>
          <el-button type="text" @click="Edit(scope.row)">编辑 </el-button>
          <el-button
            type="text"
            v-hasPermi="['datascan:tags:remove']"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--   新增/编辑 弹框-->
    <common-edit-dialog
      :title="isEdit ? '编辑重要数据' : '新增重要数据'"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :button-loading="buttonLoading"
    >
      <el-form
        ref="form"
        label-width="100px"
        :model="form"
        :rules="rules"
        @submit.native.prevent
      >
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="重要数据名称" prop="tagName">
              <common-input
                place
                v-model="form.tagName"
                :maxlength="16"
                placeholder="请输入"
              ></common-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="重要数据来源">
              <el-radio-group v-model="isKeyWord">
                <el-radio :label="1">数据分类</el-radio>
                <el-radio :label="0">关键词</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="数据分类"
              v-if="isKeyWord === 1"
              prop="typeIds"
            >
              <div class="maxRowsDiv">
                <el-cascader
                  style="width: 100%"
                  :options="treeListArr"
                  :show-all-levels="false"
                  v-model="form.typeIds"
                  :props="{
                    label: 'typeName',
                    value: 'typeId',
                    multiple: true,
                    emitPath: false,
                  }"
                  checkStrictly
                  clearable
                  ref="cascader"
                >
                  <template slot-scope="{ node, data }">
                    <common-marquee-text
                      :content="data.typeName"
                    ></common-marquee-text>
                  </template>
                </el-cascader>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关键词" v-if="isKeyWord === 0" prop="keyWord">
              <common-input
                place
                placeholder="多个关键词间用,分隔"
                v-model="form.keyWord"
              ></common-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark" show-overflow-tooltip>
              <common-input
                type="textarea"
                placeholder="请输入"
                v-model="form.remark"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
    <!--   详情弹框-->
    <common-info-dialog
      :visible="openInfo"
      :title="detailsTitle"
      @cancel="cancelInfo"
      :infoLoading="infoLoading"
    >
      <common-info-table>
        <common-info-table-cell label="重要数据名称">
          {{ info.tagName }}
        </common-info-table-cell>
        <common-info-table-cell label="重要数据来源">
          {{ info.tagSource }}
        </common-info-table-cell>
        <common-info-table-cell label="数据分类">
          {{ info.typeNames }}
        </common-info-table-cell>
        <common-info-table-cell label="关键字">
          {{ info.keyWord }}
        </common-info-table-cell>
        <common-info-table-cell label="备注">
          {{ info.remark }}
        </common-info-table-cell>
        <common-info-table-cell label="状态">
          {{ info.status === 0 ? "启用" : "停用" }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import {
  listTags,
  deleteTags,
  queryTags,
  updateStatusTags,
  updateTags,
  addTags,
  deleteForCheck,
} from "@/api/datascan/label/label";
import { queryTreeList } from "@/api/datascan/level/level";
import BaseList from "@/mixins/BaseList";
// import type from '@/views/management/configure/dict/type'

export default {
  name: "index",
  mixins: [BaseList],
  data() {
    return {
      buttonLoading: false,
      infoLoading: false,
      totalCount: 0, //总条数
      detailsTitle: "", //详情标题
      open: false, // 新增/编辑弹框
      openInfo: false, //详情弹框
      isButtonLoading: false,
      radio: "0",
      treeListArr: [],
      //查询参数
      queryParams: {
        pageNum: 1, //页
        pageSize: 10, //一页中的数据条数
        tagName: null,
        typeName: null,
        status: null,
        keyWord: null,
        typeId: null,
        tagSource: null,
      },
      //新增/编辑标题
      isEdit: false,
      valueList: [],
      //展示和隐藏input
      isKeyWord: 1, // 1 数据分类 0 关键字
      form: {
        tagId: null,
        tagName: "",
        typeIds: [],
        keyWord: "",
        remark: "",
        tagSource: "",
      },
      info: {
        tagName: "",
        content: "",
        remark: "",
        typeNames: "",
        keyWord: "",
      },
      //表单校验
      rules: {
        tagName: [
          {
            required: true,
            message: "请输入重要数据名称",
            trigger: "blur",
          },
        ],
        typeIds: [
          {
            required: true,
            message: "请选择数据分类",
            trigger: "blur",
          },
        ],
        keyWord: [
          {
            required: true,
            message: "请输入关键词",
            trigger: "blur",
          },
        ],
      },
      key: "tagId",
    };
  },
  created() {
    this.getList();
    this.queryTreeList();
  },
  methods: {
    //数据分类
    queryTreeList() {
      queryTreeList(this.queryParams).then((res) => {
        if (res && res.code === 200 && res.data && res.data.length) {
          // console.log(res)
          this.treeListArr = res.data;
        } else {
          this.treeListArr = [];
        }
      });
    },
    //启用、停用
    changeStatus(row) {
      // console.log(row)
      return new Promise((resolve, reject) => {
        let status = row.status === 0 ? 1 : 0;
        updateStatusTags({ status: status, tagId: row.tagId })
          .then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("操作成功");
              this.getList();
              resolve(res);
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
              reject();
            }
          })
          .catch(() => reject());
      });
    },

    Edit(row) {
      console.log("row: ", row);
      this.isEdit = true;
      if (row.status === 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        this.open = true;
        this.$nextTick(() => {
          this.form.tagId = row.tagId;
          this.form.tagName = row.tagName;
          this.form.keyWord = row.keyWord;
          this.form.remark = row.remark;
          this.form.typeIds = row.list.reduce((r, c) => {
            r.push(c.type_id);
            return r;
          }, []);

          if (row.list && row.list instanceof Array && row.list.length) {
            this.isKeyWord = 1;
          }
          if (row.keyWord) {
            this.isKeyWord = 0;
          }
        });
      }
    },
    //详情
    getInfo(tagId) {
      this.openInfo = true;
      this.detailsTitle = "重要数据详情";
      this.detail(tagId);
    },
    detail(tagId) {
      this.infoLoading = true;
      queryTags({ tagId }).then((res) => {
        console.log(res);
        if (res && res.code === 200) {
          this.info.tagName = res.data.tagName;
          this.info.remark = res.data.remark;
          this.info.tagSource = res.data.tagSource == 1 ? "数据分类" : "关键字";
          this.info.typeNames =
            res.data.typeNames === "null" ? "" : res.data.typeNames;
          this.info.keyWord = res.data.keyWord;
          let content = "";
          if (res.data.typeNames) {
            content = res.data.typeNames;
          }
          if (
            res.data.list &&
            res.data.list instanceof Array &&
            res.data.list.length
          ) {
            content = res.data.list
              .reduce((lr, lc) => {
                lr.push(lc.type_name);
                return lr;
              }, [])
              .join(",");
          }
          if (res.data.keyWord) {
            content = res.data.keyWord;
          }
          this.info.content = content;
          this.info.status = res.data.status;
          this.infoLoading = false;
        } else {
          this.$GlobalErrorConfirm("获取信息失败", res.msg, "重新加载").then(
            () => {
              this.detail(tagId);
            }
          );
        }
      });
    },
    //查询重要数据管理列表
    getList() {
      listTags(this.queryParams).then((res) => {
        if (res && res.code === 200) {
          this.valueList = res.data.dataList.reduce((r, c) => {
            let content = "";
            if (c.list && c.list instanceof Array && c.list.length) {
              content = c.list
                .reduce((lr, lc) => {
                  lc && lc.type_name ? lr.push(lc.type_name) : "";
                  return lr;
                }, [])
                .join(",");
            }

            r.push({
              ...c,
              content,
              isDisabledForShake: false,
              tagSource: c.tagSource == 1 ? "数据分类" : "关键字",
              typeIds: content,
            });

            return r;
          }, []);
          this.totalCount =
            res && res.data.totalCount ? res.data.totalCount : 0;
        } else {
          this.valueList = [];
          this.total = 0;
          this.handleListTips(res);
        }
      });
    },
    //弹框取消
    cancel() {
      this.form.tagId = null;
      this.form.tagName = "";
      this.form.keyWord = "";
      this.form.remark = "";
      this.form.typeIds = [];
      this.isKeyWord = 1;

      this.$refs.form.clearValidate();
      this.open = false;
    },
    cancelInfo() {
      this.openInfo = false;
    },
    //查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置按钮
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      // this.resetForm("queryForm");
    },
    //新增
    handleAdd() {
      this.open = true;
      this.isEdit = false;
      this.form.tagId = null;
    },
    //提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        let ids = "";
        if (this.isKeyWord === 1) {
          this.form.keyWord = "";
          ids = this.$refs.cascader
            .getCheckedNodes(true)
            .reduce((r, c) => {
              r.push(c.data.typeId);
              return r;
            }, [])
            .join(",");
        } else {
          this.form.typeIds = [];
        }
        if (valid) {
          let params = {
            ...this.form,
            typeIds: this.isKeyWord === 1 ? ids : null,
            tagSource: this.isKeyWord,
          };
          this.handleShake(params, "submit");
        }
      });
    },

    submitFormForShake(params) {
      this.buttonLoading = true;
      return new Promise((resolve, reject) => {
        if (this.isEdit) {
          updateTags(params)
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("编辑成功");
                this.cancel();
                this.getList();
                resolve(res);
              } else {
                this.$GlobalErrorConfirm("编辑失败", res.msg);
                reject();
              }
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        } else {
          addTags(params)
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("新增成功");
                this.cancel();
                this.getList();
                resolve(res);
              } else {
                this.$GlobalErrorConfirm("新增失败", res.msg);
                reject();
              }
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },

    //删除
    deleteData(row) {
      if (row) {
        // 单个删除
        // 1 状态为启用不给删
        if (row && row.status === 0) {
          this.$GlobalErrorConfirm("删除失败", " 启用状态下不允许删除");
          return;
        }
        // 2 关联了敏感字段 给提示
        if (row.list.length !== 0 || row.keyWord !== "") {
          this.$GlobalDeleteConfirm()
            .then(() => {
              const ids = row.tagId;
              deleteTags({ ids }).then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("删除成功");
                  if (
                    this.queryParams.pageNum > 1 &&
                    ids.split(",").length === this.valueList.length
                  ) {
                    this.queryParams.pageNum -= 1;
                  }
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("删除失败", res.msg).then();
                }
              });
            })
            .catch(() => {});
        }
      } else {
        //批量删除
        //1、判断是不是启用
        let status = this.valueList.find(
          (v) => this.ids.includes(v.tagId) && v.status === 0
        );
        if (status) {
          this.$GlobalErrorConfirm("删除失败", "状态已启用无法删除");
          return;
        }
        //2、绑定关键字给提示
        let isNull = this.valueList.find(
          (v) =>
            (this.ids.includes(v.tagId) && v.list.length !== 0) ||
            v.keyWord !== ""
        );
        if (isNull) {
          this.$GlobalDeleteConfirm()
            .then(() => {
              const ids = this.ids.join(",");
              console.log(ids);
              deleteTags({ ids }).then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("删除成功");
                  if (
                    this.queryParams.pageNum > 1 &&
                    ids.split(",").length === this.valueList.length
                  ) {
                    this.queryParams.pageNum -= 1;
                  }
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("删除失败", res.msg).then();
                }
              });
            })
            .catch(() => {});
        }
      }
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
  mounted() {},
};
</script>

<style scoped></style>
